//
//  ByUINFillCodeVC.m
//  oc_knowledge
//
//  Created by justiOS on 17/1/18.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUINFillCodeVC.h"
// net
#import "ByApiUser.h"

// vc
#import "ByUISetPSWVC.h"

// view
#import "ByViewRegisterStep.h"
@interface ByUINFillCodeVC (){
    NSInteger _countdownTime;   // 倒计时剩余时间
    NSAttributedString *_title; // 可以点击获取验证码时的标题
}
@property (nonatomic, strong) UITextField *codeTF;
@property (nonatomic, strong) UIButton *codeButton;
@property (nonatomic, strong) UIButton *timeCodeButton;
@end

@implementation ByUINFillCodeVC
#pragma mark getter
- (UITextField *)codeTF {
    if (!_codeTF) {
        _codeTF = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH - 20, 20)];
        _codeTF.placeholder = @"请输入短信中的验证码";
        _codeTF.tintColor = BY_THEME_COLOR;
        _codeTF.font = FONT(14);
        _codeTF.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _codeTF;
}

- (UIButton *)codeButton {
    if (!_codeButton) {
        _codeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _codeButton.layer.cornerRadius = 3;
        _codeButton.backgroundColor = BY_THEME_COLOR;
        [_codeButton setTitle:@"提交验证码" forState:UIControlStateNormal];
        [_codeButton addTarget:self action:@selector(codeAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _codeButton;
}

- (UIButton *)timeCodeButton {
    if (!_timeCodeButton) {
        _timeCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _timeCodeButton.frame = CGRectMake(0, 0, 120, 30);
        _timeCodeButton.titleLabel.font = FONT(14);
        _timeCodeButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, - 8);
        [_timeCodeButton setTitleColor:BY_THEME_COLOR forState:UIControlStateNormal];
        _timeCodeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_timeCodeButton addTarget:self action:@selector(getCodeAgain:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _timeCodeButton;
}


#pragma mark UI
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    [self addLeftBackBarButtonItem];
    [self addCustomItemviews:@[self.timeCodeButton] position:ByNavigationItemPositionModeRight];
    [self createViews];
    self.view.backgroundColor = TABLE_COLOR;
    
    self.view.userInteractionEnabled = true;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapEmptyAction:)];
    [self.view addGestureRecognizer:tap];

}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // 再次获取验证码定时器倒计时30秒
    _countdownTime = 30;
    NSTimer  *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(_countdownAction:) userInfo:nil repeats:YES];
    [timer fire];
}



- (void)createViews {
    ByViewRegisterStep *view = [[ByViewRegisterStep alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    view.step = RegisterStepTwo;
    [self.view addSubview:view];
    
    UILabel *mobleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, SCREEN_WIDTH, 20)];
    mobleLabel.backgroundColor = [UIColor clearColor];
    mobleLabel.font = FONT(14);
    NSString *str1 = [self.phoneNumber stringByReplacingCharactersInRange:NSMakeRange(3,4) withString:@"****"];
    NSString *str2 = [NSString stringWithFormat:@"验证码短信已经发送到%@",str1];
    mobleLabel.text = str2;
    mobleLabel.adjustsFontSizeToFitWidth = YES;
    mobleLabel.textAlignment = NSTextAlignmentCenter;
    mobleLabel.textColor = [UIColor lightGrayColor];
    [self.view addSubview:mobleLabel];
    
    
    UIView *TFBG = [[UIView alloc] initWithFrame:CGRectMake(0, 80, SCREEN_WIDTH, 40)];
    TFBG.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:TFBG];
    [TFBG addSubview:self.codeTF];

    self.codeButton.frame = CGRectMake(10, TFBG.bottom + 10, SCREEN_WIDTH - 20, 40);
    [self.view addSubview:self.codeButton];
}


#pragma mark 点击事件
// 验证验证码
- (void)codeAction:(UIButton *)button {
    if (self.codeTF.text.length != 6) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"短信验证码输入错误，请重新输入"preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            self.codeTF.text = nil;
        }];
        [alert addAction:action1];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }
    
    
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    model.mobile = _phoneNumber;
    model.code = self.codeTF.text;
    model.type = @"1";
    [ByApiUser checkCode:model success:^(ByNetBaseResult *result) {
        ByUISetPSWVC *vc = [[ByUISetPSWVC alloc] init];
        vc.type = @"1";
        vc.phoneNumber = _phoneNumber;
        vc.code = self.codeTF.text;
        [self by_normalPush:vc hasNavi:YES];
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}

// 重新获取验证码
- (void)getCodeAgain:(UIButton *)button {
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    model.mobile = _phoneNumber;
    model.type = @"1";
    [ByCoreToolAlert showLoadind:@"发送中..." hasMasker:YES];
    [ByApiUser getCode:model success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert hideHud];
        _countdownTime = 30;
        NSTimer  *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(_countdownAction:) userInfo:nil repeats:YES];
        [timer fire];
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];

}

- (void)tapEmptyAction:(UITapGestureRecognizer *)tap {
    
    [UIView animateWithDuration:0.4 animations:^{
        [self.codeTF resignFirstResponder];
    }];
}

#pragma mark - 倒计时处理
- (void)_countdownAction:(NSTimer *)timer {
    if (_countdownTime > 0) {
        self.timeCodeButton.enabled = NO;
        _countdownTime --;
        [self.timeCodeButton setTitle:[NSString stringWithFormat:@"%li秒后重新发送",_countdownTime] forState:UIControlStateNormal];
    }
    else {
        [self.timeCodeButton setTitle:@"重新发送" forState:UIControlStateNormal];
        self.timeCodeButton.enabled = YES;
        [timer invalidate];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
